<template>
    <rx-layout>
        <div slot="left" width="230" showButton="true" :headerTitle="i18n('list.userOrganization','用户组织')">
            <div style="padding: 10px 4px">
                <rx-vue-tree
                    :tree-data="orgData"
                    :label="'title'"
                    :field="'groupId'"
                    :async-tree="true"
                    :show-checkbox="false"
                    @expandClick="triggerClick"
                    @rowClick="selectGroupNode"
                    :expanded-keys.sync="expandedKeys"
                >
                </rx-vue-tree>
            </div>

        </div>

        <div slot="center" style>
            <rx-fit>
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button @click="add" icon="plus" type="primary">{{$ti18('rxList.newBtn','新建')}}</a-button>
                        <a-button
                            @click="editOne"
                            icon="edit"
                            type="primary"
                            v-if="editEnable && selectedRows.length > 0">{{$ti18('rxList.editBtn','编辑')}}
                        </a-button>
                        <a-dropdown v-if="selectedRows.length > 0">
                            <a-button @click="dimissionUserIds()" icon="stop" type="danger">{{i18n('list.leaveOffice','离职')}}
                            </a-button>
                        </a-dropdown>
                        <a-dropdown v-if="removeEnable && selectedRows.length > 0">
                            <a-button @click="delByIds(selectedRowKeys)" icon="delete" type="danger">{{$ti18('rxList.delBtn','删除')}}</a-button>
                        </a-dropdown>
                        <a-button @click="doImport" icon="import">{{$ti18('rxList.importBtn','导入')}}</a-button>
<!--                        <a-button
                            @click="syncUserOrg"
                            icon="sync"
                            type="primary"
                            v-if="syncMode!='dummy'"
                        >{{ syncModeText }}
                        </a-button>-->


                    </div>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow">
                            <i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}
                        </span>
                    </span>
                </div>
                <div slot="searchbar" searchdir="right" btnalign="right" v-if="fitSearch" @search="search"
                     @cancel="reset" @close="close">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','姓名')">
                                    <a-input :placeholder="i18n('form.name','姓名','input')" v-model="queryParam.Q_FULLNAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.accountNum','账号')">
                                    <a-input :placeholder="i18n('form.accountNum','账号','input')" v-model="queryParam.Q_USER_NO__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.lockOrNot','是否锁定')">
                                        <a-select :placeholder="i18n('form.lockOrNot','是否锁定','select')" v-model="queryParam['Q_IS_LOCK__S_EQ']"
                                                  :allowClear="true">
                                            <a-select-option value="YES">{{i18n('yes','是')}}</a-select-option>
                                            <a-select-option value="">{{i18n('no','否')}}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.userType','用户类型')">
                                        <a-select :placeholder="i18n('form.userType','用户类型','input')" v-model="queryParam['Q_os.USER_TYPE__S_EQ']"
                                                  :allowClear="true">
                                            <a-select-option :key="userType.code" v-for="userType in osUserTypes">
                                                {{ userType.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.phoneNum','手机号码')">
                                        <a-input :placeholder="i18n('form.phoneNum','手机号码','input')" v-model="queryParam.Q_MOBILE__S_LK"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.email','邮件')">
                                        <a-input :placeholder="i18n('form.email','邮件','input')" v-model="queryParam.Q_EMAIL__S_LK"/>
                                    </a-form-item>
                                </a-col>
                                <a-col v-show="showDepName" :span="colSpan">
                                    <a-form-item :label="i18n('list.departAndGroup','部门与组')">
                                        <a-input  :placeholder="i18n('list.departAndGroup','部门与组','input')" v-model="queryParam['Q_DEP_NAME__S_LK']"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('list.isHasMain','是否有主部门')">
                                        <a-select :placeholder="i18n('list.isHasMainMess','展示没有主部门的用户')" v-model="queryParam['Q_HAS_MAIN__S_EQ']"
                                                  :allowClear="true" @change="changeHasMain">
                                            <a-select-option value="NO">{{i18n('no','否')}}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan" v-if="isheader">
                                <span class="table-page-search-submitButtons">
                                    <a-button @click="$refs.table.loadData()" icon="search" type="primary">{{$ti18('rxList.searchBtn','查询')}}</a-button>
                                    <a-button @click="reset" style="margin-left: 4px">{{$ti18('rxList.resetBtn','重置')}}</a-button>
                                    <a @click="toggleAdvanced" style="margin-left: 8px">
                                        {{ advanced ? '收起' : '展开' }}
                                        <a-icon :type="advanced ? 'up' : 'down'"/>
                                    </a>
                                </span>
                                </a-col>
                            </template>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-user/user/org/osUser/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="[10,30,40]"
                    id-field="userId"
                    @selectChange="onSelectChange"
                >
                    <span slot="isLock" slot-scope="{ text, record }">
                        <a-tag :color="isLockMap[text].color">
                        <span>{{ isLockMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="status" slot-scope="{ text, record }">
                        <a-tag :color="statusMap[text].color">
                        <span>{{ statusMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span @click.stop="edit(record)" v-if="editEnable" :title="$ti18('rxList.editBtn','编辑')">{{$ti18('rxList.editBtn','编辑')}}</span>
                        <span @click.stop="setPwd(record.userId)" :title="i18n('list.setPwd','修改密码')">{{i18n('list.setPwd','修改密码')}}</span>
                        <span @click.stop="dimissionByIds([record.userId])" v-if="record.status=='1'" :title="i18n('list.leaveOffice','离职')">{{i18n('list.leaveOffice','离职')}}</span>
                        <span @click.stop="delByIds([record.userId])" v-if="removeEnable" :title="$ti18('rxList.delBtn','删除')">{{$ti18('rxList.delBtn','删除')}}</span>
                        <span @click.stop="unlock(record.userId)" v-if="record.isLock=='YES'"  :title="i18n('list.unlock','解锁')">{{i18n('list.unlock','解锁')}}</span>

                        <span  @click.stop="viewPermission(record)" :title="i18n('list.view','查看权限')">
                            {{i18n('list.view','查看权限')}}
                        </span>
                    </span>
                </rx-grid>
                <a-modal
                    :title="i18n('list.setResignTime','设置离职时间')"
                    style="top: 100px;"
                    :width="400"
                    v-model="visible"
                    :confirmLoading="confirmLoading"
                    @ok="handleOk"
                >
                    <a-date-picker :getCalendarContainer="p=>p.parentNode" show-time :placeholder="i18n('list.setResignTime','设置离职时间')" @ok="onOk"/>
                </a-modal>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import OsUserApi from '@/api/user/org/osUser'
import OsGroupApi from '@/api/user/org/osGroup'
import OsusertypeApi from '@/api/user/org/osUserType'
import OsUserEdit from './OsUserEdit'
import OsUserUpdatePwd from './OsUserUpdatePwd'
import OsUserSyncApi from '@/api/user/org/osUserSync';
import OsUserImport from "./OsUserImport.vue";

import {BaseList, Util, RxLayout, RxFit, RxGrid, RxVueTree} from "@lowcode/jpaas-common-lib"
import DialogBox from "@/assets/js/DialogBox";
import OsUserViewPermission from "@/views/modules/user/org/OsUserViewPermission";

export default {
    name: 'OsUserList',
    mixins: [BaseList],
    components: {
        OsUserImport,
        RxLayout,
        RxFit,
        RxGrid,
        RxVueTree
    },
    data() {
        return {
            showDepName: true,
            expandedKeys:[],
            table: 'table',
            orgData: [],
            userId: '',
            visible: false,
            quitUserIds: [],
            confirmLoading: false,
            quitTime: "",
            osUserTypes: [],
            // 表头
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    width: 60,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                },
                {

                    title: this.i18n('form.name','姓名'),
                    width: 100,
                    dataIndex: 'fullName'
                },
                {

                    title: this.i18n('form.accountNum','账号'),
                    width: 120,
                    dataIndex: 'userNo'
                },
                {

                    title: this.i18n('form.userType','用户类型'),
                    width: 100,
                    dataIndex: 'userTypeName'
                },
                {

                    title: this.i18n('form.email','邮件'),
                    width: 140,
                    dataIndex: 'email'
                },
                {

                    title: this.i18n('form.lockOrNot','是否锁定'),
                    width: 80,
                    dataIndex: 'isLock',
                    scopedSlots: {customRender: 'isLock'}
                },
                {

                    title: this.i18n('form.status','状态'),
                    width: 80,
                    dataIndex: 'status',
                    scopedSlots: {customRender: 'status'}
                },
                {
                    width: 130,
                    title: this.$ti18('rxList.action','操作'),
                    dataIndex: 'action',
                    scopedSlots: {customRender: 'action'}
                }
            ],
            isLockMap: {
                "YES": {color: 'red', text: this.i18n('yes','是')},
                "NO": {color: 'green', text: this.i18n('no','否')},
                "": {color: 'green', text: this.i18n('no','否')}
            },
            statusMap: {
                "1": {color: 'green', text: this.i18n('active','在职')},
                "0": {color: 'red', text: this.i18n('list.leaveOffice','离职')},
                "": {color: 'red', text: '无'}
            },
            component: OsUserEdit,
            comment: this.i18n('list.user','用户'),
            widthHeight: ['1200px', '700px'],

            syncMode: "dummy",
            syncModeText: "",
            syncModeObj: {"dd": this.i18n('list.syncDingTalk','同步钉钉'), "weixin": this.i18n('list.syncWeChat','同步微信')},
        }
    },
    filters: {},
    created() {
        this.loadAdminDeps();
        this.getAllUserTypeList();
        //获取同步配置
        this.getSyncConfig();

    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"osUser",key);
        },
        getAppQuery(){
            var query={};
            if(this.curApp.appId){
                query.appId=this.curApp.appId;
                query.appName=this.curApp.appName;
            }
            return query;
        },
        viewPermission(record){
            // 查看权限
            var self = this;
            Util.open({
                component:OsUserViewPermission,
                curVm: self,
                max:true,
                title: self.i18n('list.view','查看权限'),
                data: {
                    userId: record.userId,
                    fullName: record.fullName
                }
            }, function (action) {
            });
        },
        search() {
            this.$refs.table.loadData()
        },
        reset(){
            this.queryParam={};
            this.showDepName=true
            this.resetSearch();
        },
        close() {
            //关闭按钮
            this.fitSearch = false;
        },

        delById(ids) {
            return OsUserApi.delOsUser({ids: ids.join(',')});
        },
        dimissionByIds(ids) {
            this.visible = true;
            this.quitUserIds = ids;
        },
        getListByParams(parameter) {
            return OsUserApi.getOsUserList(parameter)
        },
        //加载部门树
        loadAdminDeps() {
            OsGroupApi.getAdminOrg().then(resp => {
                let data = resp.data;
                let temp = [];
                for (let i = 0; i < data.length; i++) {
                    let rs = data[i];
                    let obj = {title: rs.name, groupId: rs.groupId, key: rs.key}
                    if(rs.childAmount){
                        obj.children = [] ;
                    }
                    temp.push(obj)
                }
                this.orgData = [...temp];
                this.expandedKeys.push(temp[0].groupId);
                this.triggerClick(true,temp[0])
            })
        },
        async triggerClick(trigger,tree){
            if(trigger && tree.children && tree.children.length > 0){
                return ;
            }else {
                let data = await OsGroupApi.getParentGroup(tree.groupId);
                let treeData = []
                for (let i = 0; i < data.length; i++) {
                    let res = data[i]
                    let obj = {title: res.name, groupId: res.groupId, key: res.key}
                    if(res.childAmount){
                        obj.children = []
                    }
                    treeData.push(obj)
                }
                let orgData = this.getGroupTree(this.orgData, tree.groupId, treeData);

                this.orgData = [...orgData];
            }
        },
        getGroupTree(orgData, groupId, treeData) {
            if (treeData.length > 0) {
                for (var i = 0; i < orgData.length; i++) {
                    if (orgData[i].groupId == groupId) {
                        orgData[i].children = treeData;
                        break;
                    }
                    if (orgData[i].children) {
                        this.getGroupTree(orgData[i].children, groupId, treeData);
                    }
                }
            }
            return orgData;
        },
        //选中树节点
        selectGroupNode(tree,parentData,select) {
            //查询左树用户
            if (!select) {
                delete this.queryParam.groupId;
            } else {
                this.queryParam.groupId = tree.groupId;
            }
            this.$refs.table.loadData()
        },
        onOk(value) {
            this.quitTime = value.format("YYYY-MM-DD HH:mm:ss");
        },
        handleOk() {
            this.confirmLoading = true;
            return OsUserApi.dimissionByIds({ids: this.quitUserIds.join(','), quitTime: this.quitTime}).then(res => {
                this.quitTime = "";
                this.visible = false;
                this.confirmLoading = false;
                if (res.success) {
                    this.$refs.table.loadData();
                }
            });
        },
        dimissionUserIds() {
            if (this.selectedRows.length > 0) {
                var dimission = [];
                for (var i = 0; i < this.selectedRows.length; i++) {
                    if (this.selectedRows[i].status == '1') {
                        dimission.push(this.selectedRows[i].userId);
                    }
                }
                if (dimission.length > 0) {
                    this.dimissionByIds(this.selectedRowKeys);
                } else {
                    this.$message.error(this.i18n('hasResigned','所选用户已离职!'));
                }
            } else {
                this.$message.warning(this.i18n('selectUser','请选择用户!'));
            }
        },
        setPwd(userId) {
            var self = this;
            Util.open({
                component: OsUserUpdatePwd,
                curVm: self,
                widthHeight: ['800px', '400px'],
                title: this.i18n('list.setPwd','修改密码'),
                data: {userId: userId, individual: false}
            }, function (action) {
            });
        },
        getAllUserTypeList() {
            OsusertypeApi.getAllUserTypeList().then(data => {
                this.osUserTypes = data;
            });
        },
        getSyncConfig() {
            OsUserSyncApi.getSyncConfig().then(res => {
                this.syncMode = res;
                this.syncModeText = this.syncModeObj[res];
            })
        },
        syncUserOrg() {
            var key = "syncUserOrg";
            this.$message.loading({content: this.i18n('Synchronizing','正在同步组织架构和用户，请稍候...'), key});

            OsUserSyncApi.syncOrgUser().then(res => {
                if (res.success) {
                    this.$refs.table.loadData();
                    this.$message.success({content: this.i18n('SyncSuccess','同步组织架构成功'), key, duration: 2});
                }
            });
        },
        doImport() {
            var self = this;
            Util.open(
                {
                    component: OsUserImport,
                    curVm: this,
                    widthHeight: ['700px', '500px'],
                    title: this.i18n('importUsers','导入用户'),
                }, function (action) {
                    if (action == "ok") {
                        self.search(); //刷新数据
                    }
                });
        },
        unlock(userId) {
            var self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips','操作提示'),
                content: this.i18n('sureToUnLock','您确定需要解锁选中的记录吗'),
                okText: this.$ti18('rxForm.okBtn','确定'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                onOk() {
                    OsUserApi.unlockAccount({userId: userId}).then(res => {
                        if (res.success) {
                            self.$refs.table.loadData();
                        }

                    });
                },
                onCancel() {
                },
            })

        },
        //重写add方法,增加自定义参数
        add() {
            var conf = {
                component: this.component,
                title: this.$ti18('rxList.newBtn','添加') + '-' + this.comment,
                urlType: 'Add',
                widthHeight: this.widthHeight,
                data: {
                    groupId: this.queryParam.groupId,
                    relTypeId: "1"
                },
            };
            this.handleEdit(conf);
        },
        changeHasMain(e){
            if (e=="NO"){
                delete this.queryParam['Q_DEP_NAME__S_LK']
                this.showDepName=false
            }else {
                this.showDepName=true
            }
        }
    }
}
</script>
<style scoped>


* > > > .gridFooter {
    padding-bottom: 0;
}
</style>

